/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.support.alipay;

import com.yanlight.Constants;
import com.yanlight.support.alipay.request.AlipayNotifyPayRequest;
import com.yanlight.support.pay.PayNotify;
import com.yanlight.support.pay.PayNotifyHandler;
import com.yanlight.support.pay.PayNotifyRequest;
import com.yanlight.type.PayType;
import com.yanlight.util.LogUtil;
import com.yanlight.util.WebUtil;

import javax.servlet.http.HttpServletResponse;

/**
 * @author haolw
 * @time 2017/10/27
 */
public class AlipayNotifyHandler implements PayNotifyHandler {
    private static AlipayNotifyHandler handler = new AlipayNotifyHandler();

    private AlipayNotifyHandler() {
    }

    public static AlipayNotifyHandler getInstance() {
        return handler;
    }

    @Override
    public void handPayNotify(String packets, HttpServletResponse response, PayNotify notify) {

        AlipayNotifyPayRequest notifyRequest = new AlipayNotifyPayRequest(packets);
        String publicKey = AlipayConstants.publicKey;
        if (notifyRequest.verifySign(publicKey)) {
            PayNotifyRequest payNotifyRequest = new PayNotifyRequest();
            payNotifyRequest.setBuyerId(notifyRequest.getBuyerId());
            payNotifyRequest.setOutTradeNo(notifyRequest.getOutTradeNo());
            payNotifyRequest.setTransactionNo(notifyRequest.getTradeNo());
            payNotifyRequest.setPayTime(notifyRequest.getGmtPayment());
            payNotifyRequest.setPayType(PayType.ALIPAY.getType());
            payNotifyRequest.setTotalFee(Double.valueOf(notifyRequest.getTotalAmount()));
            boolean internalResult = notify.processPayNotify(payNotifyRequest);
            if (internalResult) {
                WebUtil.renderText(response, Constants.SUCCESS);
            }
        } else {
            WebUtil.renderText(response, Constants.FAIL);
        }
    }

}
